import { useState } from "react";
import { Text, View } from "@tarojs/components";
import Taro, { useRouter } from "@tarojs/taro";
import { useMap, useUpdateEffect } from "ahooks";
import pick from "lodash-es/pick";

import dayjs from "dayjs";
import isSameOrAfter from "dayjs/plugin/isSameOrAfter"; // ES 2015
import isSameOrBefore from "dayjs/plugin/isSameOrBefore"; // ES 2015

import ByTag from "@/components/ui/ByTag";
import ByIcon from "@/components/ui/ByIcon";
import ByRow from "@/components/ui/ByRow";
import ByText from "@/components/ui/ByText";
import Page from "@/components/common/Page";
import BySpace from "@/components/ui/BySpace";
import ByButton from "@/components/ui/ByButton";
import ListView from "@/components/app/ListView";
import ByCellGroup from "@/components/ui/ByCellGroup";
import CustomerCard from "@/components/app/CustomerCard";
import PopupAddWorker from "./components/PopupAddWorker";
import DispatchRecord from "./components/DispatchRecord";

import ApiCrm from "@/api/crm";
import useList from "@/hooks/useList";
import useFetch from "@/hooks/useFetch";

import { DispatchListItem, DispatchWorker } from "@/types/dispatch";
import { IntentCustomerData } from "@/types/customer";

dayjs.extend(isSameOrAfter);
dayjs.extend(isSameOrBefore);

const tagMap = {
  1: { color: "primary", label: "已开工" },
  2: { color: "success", label: "已完工" },
}

const ProposedCard = ({
  source,
  workers,
  border = true,
  onSelected,
}: {
  source: DispatchListItem
  workers: DispatchListItem["workers"];
  border: boolean;
  onSelected?: () => void;
}) => {

  const { completeState, startState } = source

  const isStarted = startState === 1
  const isCompleted = completeState === 1

  const tag = tagMap[isCompleted ? 2 : isStarted ? 1 : 0]

  const renderWorkers = isCompleted ? source.workers : workers

  return (
    <View className={`py-4 border-line-light ${border && "border-t-1 "}`}>
      <View className="flex items-center mb-3">
        <View className="flex-auto">
          <ByRow align="center">
            <ByText size="sm" className="mr-2">{source.workerType}</ByText>
            {
              tag && <ByTag type={tag.color} size="small" variant="filled">{tag.label}</ByTag>
            }
          </ByRow>

          <ByText type="third" size="sm" className="mt-2">
            <Text>{source.planStartDate}</Text>
            <Text className="px-1">~</Text>
            <Text>{source.planEndDate}</Text>
          </ByText>
        </View>

        {
          !isCompleted && <ByIcon name="PlusCircle" size={42} onClick={onSelected} />
        }
      </View>

      <BySpace>
        {renderWorkers?.map((worker) => (
          <ByTag variant="outline" size="small" rounded={false}>
            {worker.workerName}
          </ByTag>
        ))}
      </BySpace>
    </View>
  );
};

const dispatchWorkerKeysFromList = [
  "planId",
  "constructionPeriod",
  "planStartDate",
  "planEndDate",
];

const dispatchWorkerKeysForCoutomer = [
  "customerNo",
  "intentCustomerId",
  "customerName",
];

const dispatchWorkerKeysForWorker = ["workerId", "workerName", "workerType"];

export default () => {
  const { params } = useRouter();
  const intentCustomerId = Number(params.intentCustomerId);

  const [selected, setSelected] = useState<DispatchListItem>();

  // 存储已选工人
  const [model, { get, set, setAll }] = useMap<string, DispatchWorker[]>();

  // 获取客户详情
  const { data } = useFetch<IntentCustomerData>(ApiCrm.customerDetail, {
    showLoading: true,
    defaultParams: [{ intentCustomerId }],
    onAfter: (res) => res.intentCustomer,
  });

  // 获取可分派项目列表
  const {
    list,
    loading: loadingForList,
    refresh: refreshDiapatchList,
  } = useList<DispatchListItem>(
    ApiCrm.getDispatchList,
    { defaultParams: [{ intentCustomerId }] }
  );

  useUpdateEffect(() => {
    if (list.length > 0) {
      const map = new Map();
      list?.forEach((item) => {
        if (item.completeState !== 1) {
          map.set(item.workerType, item.workers || []);
        }
      });
      setAll(map);
    }
  }, [list])

  // 添加选中的工人
  const handleSetMap = (list: any[]) => {
    const res = list.map((e) => {
      return {
        ...pick(data, dispatchWorkerKeysForCoutomer),
        ...pick(selected, dispatchWorkerKeysFromList),
        ...pick(e, dispatchWorkerKeysForWorker),
      };
    });
    set(selected!.workerType, res);
    setSelected(undefined);
  };

  const formHandle = useFetch(ApiCrm.dispatch, "POST", {
    manual: true,
    onSuccess() {
      Taro.showToast({ title: "提交成功" });
      // 刷新数据
      refreshDiapatchList();
    },
  });

  const handleSubmit = () => {
    const workers = [...model.entries()].reduce((obj: any, [key, value]) => {
      Reflect.set(obj, key, value.map(e => ({
        ...e,
        planEndDate: e.planEndDate || e.endDate,
        planStartDate: e.planStartDate || e.startDate,

      })));
      return obj;
    }, {} as any);
    formHandle.run({ workers });
  };

  // 存在可派工的，显示btn
  const showBtn = list.find((e) => e.completeState !== 1);
  return (
    <>
      <Page
        footerSticky
        slotFooter={
          showBtn && <ByButton
            size="large"
            className="w-2/3"
            loading={formHandle.loading}
            onClick={handleSubmit}
          >
            提交
          </ByButton>
        }
      >

        <CustomerCard source={data} />

        <View className="p-4">
          <ByCellGroup title="派工列表" className="mt-6">
            <ListView
              loading={loadingForList}
              isEmpty={list.length === 0}
              emptyText={"暂无可派工项"}
            >
              {list?.map((item, index) => (
                <ProposedCard
                  key={index}
                  source={item}
                  border={index != 0}
                  workers={get(item.workerType) || []}
                  onSelected={() => setSelected(item)}
                />
              ))}
            </ListView>
          </ByCellGroup>
        </View>

        <DispatchRecord intentCustomerId={intentCustomerId} />
      </Page>

      {!!selected && (
        <PopupAddWorker
          // workTypeList={workTypeList}
          defaultWorkerType={selected?.workerType}
          selectedWorker={get(selected.workerType) || []}
          onConfirm={(list) => handleSetMap(list)}
          onCancel={() => setSelected(undefined)}
        />
      )}
    </>
  );
};
